﻿using System.Text.RegularExpressions;

namespace Md.Api.DDD;
/// <summary>
/// 实体帮助类
/// </summary>
public class ModelHelp
{
    /// <summary>
    /// 克隆实体，将S实体，克隆到D实体，最终返回D实体
    /// </summary>
    /// <typeparam name="D">克隆实体</typeparam>
    /// <typeparam name="S">被克隆实体</typeparam>
    /// <param name="s">被克隆实体</param>
    /// <returns>D</returns>
    public static D CloneProperty<D, S>(S s)
    {
        D d = Activator.CreateInstance<D>();

        if (s != null)
        {
            var types = s.GetType();
            var typed = typeof(D);

            foreach (var sp in types.GetProperties())
            {
                foreach (var dp in typed.GetProperties())
                {
                    var nameList = dp.Name.Split("_");
                    var newName = nameList[0] + String.Join("", nameList.Where(w => w != nameList[0]).Select(s => Regex.Replace(s, "^[a-z]", m => m.Value.ToUpper())));

                    if (sp.Name == newName)
                    {
                        dp.SetValue(d, sp.GetValue(s, null), null);
                    }
                }
            }
        }

        return d;
    }

}

